package com.shp.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shp.pojo.*;
import com.shp.service.*;
import com.shp.utils.CheckCodeUtil;
import com.shp.utils.DateUtil;
import com.shp.utils.OnlineUserUtil;
import com.shp.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author ZWL
 * @version : 1.0
 * @date : 2020/2/23 13:13
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private PurseService purseService;

    @Autowired
    private NeedService needService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrdersService ordersService;

    /**
     * 获取生成验证码显示到界面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response) {
        //设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");
        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        try {
            //输出图片方法
            CheckCodeUtil.getCheckCode(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册
     *
     * @param user 注册的用户
     * @return ResultInfo
     */
    @RequestMapping(value = "/checkRegister")
    @ResponseBody
    public ResultInfo add(@RequestBody User user, HttpSession session) {
        //响应的信息对象
        ResultInfo info = new ResultInfo();
        //注册
        return userService.register(user, session, info);
    }

    /**
     * 登陆验证
     *
     * @param user    用户信息
     * @param request HttpServletRequest
     * @return ResultInfo
     */
    @ResponseBody
    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
    public ResultInfo loginCheck(User user, HttpServletRequest request) {
        // 如果重复登陆,移除前者
        String email = user.getEmail();
        if(OnlineUserUtil.isOnline(user.getEmail())){
            OnlineUserUtil.reduceSession(email);
        }
        //验证
        return userService.loginCheck(user, request.getSession());
    }

    /**
     * 用户退出
     * 重定向到主页面
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        User activeUser = (User)session.getAttribute("activeUser");
        try{
            OnlineUserUtil.reduceSession(session);
            OnlineUserUtil.removeUserEmail(activeUser.getEmail());
            session.invalidate();
        }catch (Exception e){
            e.printStackTrace();
            // 日志
        }
        return "redirect:/home";
    }

    /**
     * 添加商品到购物车
     *
     * @param id 商品id
     * @return ResultInfo
     */

    @RequestMapping(value = "/addNotice/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo addShopCart(@PathVariable("id") Integer id, HttpServletRequest request) {
        ResultInfo info = new ResultInfo();
        User activeUser = (User)request.getSession().getAttribute("activeUser");
        Integer userId = activeUser.getId();
        // 判断是否是自己的商品
        if(goodsService.getUserByUserIdAndGoodsId(id,userId) != null){
            info.setErrorMsg("不可以购买自己额商品");
            return info;
        }
        return userService.addNotice(id, request, info);
    }

    /**
     * 忘记密码
     *
     * @return ResultInfo
     */
    @RequestMapping(value = "/password/forget", method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo forgotPassword(@RequestBody User user) {
        ResultInfo info = new ResultInfo();
        return userService.forgetPassword(user.getEmail(), info);
    }

    /**
     * 添加商品到收藏夹
     *
     * @param id      商品id
     * @param session 会话session
     * @return ResultInfo的json数据
     */
    @RequestMapping(value = "/collection/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultInfo collectionGoods(@PathVariable("id") Integer id, HttpSession session) {
        ResultInfo info = new ResultInfo();
        return userService.collectionGoods(id, session, info);
    }

    /**
     * 用户中心，查询求购信息
     * @return "user/basic"
     */
    @RequestMapping(value = "/space", method = {RequestMethod.GET})
    public String personSpace(Model model, HttpSession session) {
        User activeUser = (User) session.getAttribute("activeUser");
        Integer userId = activeUser.getId();
        /*
        个人信息,钱包，信誉值
         */
        this.template(model,userId);

        /*
        查询求购信息
         */
        // 每页显示10条记录
        int pageSize = 10;
        List<Need> needList = null;
        // 获取第pn页，pageSize条数据
        PageHelper.startPage(1,pageSize);
        needList = needService.getNeedAll();
        // 封装分页信息,连续显示一页
        PageInfo<Need> pageInfo = new PageInfo<>(needList,1);
        model.addAttribute("info",pageInfo);
        return "user/basic";
    }


    /**
     * 用户中心，查询求购信息,分页
     * @param pn 页码
     * @return pageInfo
     */
    @RequestMapping(value = "/space/need/{pn}", method = {RequestMethod.POST})
    @ResponseBody
    public PageInfo<Need> needPages(@PathVariable("pn") Integer pn) {
        if(pn != 0){
         /*
        查询求购信息
         */
            // 每页显示10条记录
            int pageSize = 10;
            List<Need> needList = null;
            // 获取第pn页，pageSize条数据
            PageHelper.startPage(pn,pageSize);
            needList = needService.getNeedAll();
            // 封装分页信息,连续显示一页
            PageInfo<Need> pageInfo = new PageInfo<>(needList, 1);
            return pageInfo;
        }
        return null;
    }

    /**
     * 保存求购信息
     * @param need 求购信息
     * @param session HttpSession
     * @return ResultInfo
     */
    @RequestMapping(value = "/space/need",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo saveNeedDetail(@RequestBody Need need,HttpSession session){
        ResultInfo info = new ResultInfo();
        // 获取在线用户
        User activeUser = (User)session.getAttribute("activeUser");
        // 获取用户id
        Integer userId = activeUser.getId();
        // 设置用户id
        need.setUser_id(userId);
        // 设置求购时间
        need.setStart_date(DateUtil.getNowDate());
        // 设置求购状态
        need.setStatus((byte) 0);
        // 保存
        if(needService.saveNeed(need)){
            info.setFlag(true);
        }
        return info;
    }



    /**
     * 我的钱包
     *
     * @return "user/wallet"
     */
    @RequestMapping(value = "/space/purse", method = RequestMethod.GET)
    public String getMyPurse(HttpSession session, Model model) {
        User activeUser = (User) session.getAttribute("activeUser");
        Integer userId = activeUser.getId();
         /*
        个人信息,钱包，信誉值
         */
        this.template(model,userId);
        return "user/wallet";
    }

    /**
     * 充值与提现 根据传过来的两个值进行判断是充值还是提现
     * @param session HttpSession
     * @param recharge 充值金额
     * @param withdrawals 提现金额
     * @return "{'flag':'false'}" 或者 "{'flag':'true'}"
     */
    @RequestMapping(value = "/space/purse",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo updatePurse(HttpSession session,
                              @RequestParam(value = "recharge",required = false)Float recharge,
                              @RequestParam(value = "withdrawals",required = false)Float withdrawals) {
        User activeUser = (User) session.getAttribute("activeUser");
        Integer userId = activeUser.getId();
        String msg = null;
        ResultInfo info = new ResultInfo();
        if(recharge == null && withdrawals == null){
            return info;
        }
        if (recharge != null) {
            // 充值金额信息对象
            Recharge recharge1 = new Recharge();
            recharge1.setUser_id(userId);
            recharge1.setRecharge(recharge);
            // 设置充值金额，初始状态0，未审核
            recharge1.setStatus((byte) 0);
            recharge1.setTime(DateUtil.getNowTime());
            recharge1.setOrderId(UuidUtil.getUuid());
            // 插入
            purseService.insertRecharge(recharge1);
            info.setFlag(true);
            info.setDatas(recharge1);
        }
        if (withdrawals != null) {
            // // 体现金额信息对象
            // Withdrawals withdrawals1 = new Withdrawals();
            // withdrawals1.setUser_id(userId);
            // withdrawals1.setWithdrawals(withdrawals);
            // // 设置体现金额，初始状态0，未审核
            // withdrawals1.setStatus((byte) 0);
            // withdrawals1.setTime(DateUtil.getNowTime());
            // // 插入
            // purseService.insertWithdrawals(withdrawals1);
            info.setErrorMsg("抱歉，此服务暂未开放");
        }
        return info;
    }

    /**
     * 个人信息
     * @param model Model
     * @param session HttpSession
     * @return "user/msg"
     */
    @RequestMapping(value = "/space/msg",method = RequestMethod.GET)
    public String personMsg(Model model,HttpSession session){
        User activeUser = (User) session.getAttribute("activeUser");
        Integer userId = activeUser.getId();
        /*
        个人信息,钱包，信誉值
         */
        this.template(model,userId);
        return "user/msg";
    }

    /**
     * 修改个人信息
     * @param user User
     * @param session HttpSession
     * @return "{'flag':'false'}" 或者 "{'flag':'true'}"
     */
    @RequestMapping(value="/space/msg",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo updatePersonMsg(User user,HttpSession session){
        ResultInfo info = new ResultInfo();
        // 获取用户的id
        User activeUser = (User)session.getAttribute("activeUser");
        int userId = activeUser.getId();
        user.setId(userId);
        // 修改个人信息
        if(userService.updateUser(user)){
            info.setFlag(true);
        }
       return info;
    }

    /**
     * 我的商品
     * @return "/user/goodsList"
     */
    @RequestMapping(value = "/space/goods",method = RequestMethod.GET)
    public String myGoods(Model model,HttpSession session){
        User activeUser = (User) session.getAttribute("activeUser");
        Integer userId = activeUser.getId();
        /*
        个人信息,钱包，信誉值
         */
        this.template(model,userId);
        /*
        用户的商品
         */
        // 每页显示6条记录
        List<GoodsExtend> goodsList = goodsService.getUserGoods(userId);
        // 预先显示页码 5
        model.addAttribute("list",goodsList);
        return "/user/goodsList";
    }

    /**
     * 获取商品的信息，便于修改
     * @param id 商品id
     * @return Good
     */
    @RequestMapping(value = "/space/goods/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Good getUserGoods(@PathVariable("id") Integer id){
        return goodsService.getGoodsByGoodsId(id);
    }

    /**
     * 修改上架商品的信息
     * @param goods Good
     * @return ResultInfo
     */
    @RequestMapping(value = "/space/goods",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo updateUserGoodsMsg(@RequestBody Good goods){
        ResultInfo info = new ResultInfo();
        if(goods == null || goods.getId() == null){
            info.setErrorMsg("服务器错误，请稍后重试");
            return info;
        }
        if(goodsService.updateGoods(goods)){
            info.setFlag(true);
            return info;
        }
        info.setErrorMsg("修改失败");
        return info;
    }

    /**
     * 删除下架的商品
     * @return
     */
    @RequestMapping(value = "/space/goods/{id}",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo delOutGoods(@PathVariable("id") Integer id){
        ResultInfo info = new ResultInfo();
        if(id != null){
            if(goodsService.deleteGoods(id)){
                info.setFlag(true);
                return info;
            }
        }
        info.setErrorMsg("删除失败");
        return info;
    }

    /**
     * 下架商品
     * @param id 商品id
     * @return GoodsExtend
     */
    @RequestMapping(value = "/space/outG/{id}",method = RequestMethod.POST)
    @ResponseBody
    public GoodsExtend outGoods(@PathVariable("id") Integer id,HttpSession session){
        ResultInfo info = new ResultInfo();
        User activeUser = (User)session.getAttribute("activeUser");
        Integer userId = activeUser.getId();
        if(id != null){
            Good goods = new Good();
            goods.setId(id);
            goods.setEnd_time(DateUtil.getNowTime());
            goods.setStatus((byte) 0);
            if(goodsService.updateGoods(goods)){
                // 查询该商品
                return goodsService.getUserByUserIdAndGoodsId(id,userId);
            }
        }
        return null;
    }

    /**
     * 系统信息
     * @param model Model
     * @param session HttpSession
     * @return "user/systemMsg"
     */
    @RequestMapping(value = "/space/sys",method = RequestMethod.GET)
    public String systemMsg(Model model,HttpSession session){
        User activeUser = (User) session.getAttribute("activeUser");
        Integer userId = activeUser.getId();
        /*
        个人信息,钱包，信誉值
         */
        this.template(model,userId);
        /*
        系统信息
         */
       List<SystemMsg> systemMsgList = userService.getSystemMsgList();
       model.addAttribute("msgList",systemMsgList);
        return "user/systemMsg";
    }

    /**
     * 我的订单
     * @param model Model
     * @param session HttpSession
     * @return "user/myOrders"
     */
    @RequestMapping(value = "/space/orders",method = RequestMethod.GET)
    public String myOrders(Model model,HttpSession session){
        User activeUser = (User) session.getAttribute("activeUser");
        Integer userId = activeUser.getId();
        /*
        个人信息,钱包，信誉值
         */
        this.template(model,userId);
        /*
        我买的，我卖的
         */
        List<Orders> myOrdersList = ordersService.getMyOrders(userId);
        List<Orders> userOrdersList = ordersService.getUserOrders(userId);
        model.addAttribute("myOrdersList",myOrdersList);
        model.addAttribute("userOrdersList",userOrdersList);
        return "user/myOrders";
    }

    /**
     * 删除订单
     * @param orders Orders
     * @param session HttpSession
     * @return ResultInfo
     */
    @RequestMapping(value = "/ordersDel",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo ordersDel(@RequestBody Orders orders,HttpSession session){
        ResultInfo info = new ResultInfo();
        boolean flag = false;
        if(orders.getUser_id() == null){
            User activeUser = (User) session.getAttribute("activeUser");
            Integer userId = activeUser.getId();
            flag = ordersService.deleteOrdersByUserAndId(userId,orders.getId());
        }else{
            flag = ordersService.deleteOrdersByUserAndId(orders.getUser_id(),orders.getId());
        }
        info.setFlag(flag);
        return info;
    }

    /**
     * 确认收货
     * @param orders Orders
     * @param session HttpSession
     * @return ResultInfo
     */
    @RequestMapping(value = "/ordersYes",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo ordersYes(@RequestBody Orders orders,HttpSession session){
        ResultInfo info = new ResultInfo();
        User activeUser = (User) session.getAttribute("activeUser");
        Integer userId = activeUser.getId();
        orders.setUser_id(userId);
        orders.setOrder_state(3);
        boolean flag = ordersService.setOrdersStatusByUserAndId(orders);
        info.setFlag(flag);
        return info;
    }

    /**
     * 发货
     * @param orders Orders
     * @param session HttpSession
     * @return ResultInfo
     */
    @RequestMapping(value = "/ordersPush",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo ordersPush(@RequestBody Orders orders,HttpSession session){
        ResultInfo info = new ResultInfo();
        orders.setOrder_state(2);
        boolean flag = ordersService.setOrdersStatusByUserAndId(orders);
        info.setFlag(flag);
        return info;
    }


    public void template(Model model,Integer userId){
        /*
        个人信息,钱包，信誉值,系统信息
         */
        User user = userService.getUserById(userId);
        Purse purse = purseService.getPurseByUserId(userId);
        int sys = userService.getSystemMsgList().size();
        int num = needService.getNeedNum(1);
        model.addAttribute("user", user);
        model.addAttribute("num",num);
        model.addAttribute("sys",sys);
        model.addAttribute("purse", purse);
    }
}
